package com.example.demo.dao;


import com.example.demo.bean.PurchaseOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class PurchaseOrderDao {
    @Autowired
    JdbcTemplate template;

    public int getCount() {
        return template.queryForObject("SELECT COUNT(*) FROM purchaseorder", Integer.class);
    }

    public int addPurchaseOrder(PurchaseOrder purchaseOrder) {
        String sql = "INSERT INTO purchaseorder (admin_id, order_date, total_amount, status) VALUES (?, ?, ?, ?)";
        return template.update(sql,
                purchaseOrder.getAdmin_id(),
                purchaseOrder.getOrder_date(),
                purchaseOrder.getTotal_amount(),
                purchaseOrder.getStatus());
    }

    public int updatePurchaseOrder(PurchaseOrder purchaseOrder) {
        String sql = "UPDATE purchaseorder SET admin_id = ?, order_date = ?, total_amount = ?, status = ? WHERE order_id = ?";
        return template.update(sql,
                purchaseOrder.getAdmin_id(),
                purchaseOrder.getOrder_date(),
                purchaseOrder.getTotal_amount(),
                purchaseOrder.getStatus(),
                purchaseOrder.getOrder_id());
    }

    public int deletePurchaseOrder(int order_id) {
        return template.update("DELETE FROM purchaseorder WHERE order_id = " + order_id);
    }

    public List<PurchaseOrder> getAllPurchaseOrders(int page, int limit) {
        List<PurchaseOrder> list = template.query("select * from purchaseorder limit ?,?", new Object[]{(page - 1) * limit, limit},
                new BeanPropertyRowMapper(PurchaseOrder.class));
        if (!list.isEmpty()){
            return list;
        } else {
            return null;
        }
    }

    public int getCountByStatus(String status) {
        String sql = "SELECT COUNT(*) FROM purchaseorder WHERE status = ?";
        return template.queryForObject(sql, Integer.class, status);
    }



    public List<PurchaseOrder> findPurchaseOrdersById(String order_id) {
        List<PurchaseOrder> list = template.query("select * from purchaseorder where order_id = '" + order_id + "'",
                new BeanPropertyRowMapper(PurchaseOrder.class));
        if (order_id != "") {
            return list;
        } else {
            return template.query("select * from purchaseorder ", new BeanPropertyRowMapper(PurchaseOrder.class));
        }
    }

    public int getOrderDetailCountInOrder(int order_id){
        return template.queryForObject("select count(*) from purchaseorderdetail where order_id = ?", Integer.class, order_id);
    }





}
